package com.qjcc.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.qjcc.R;
import com.qjcc.util.AppUtil;
import com.qjcc.util.HttpAccessUtilsVersion2;
import com.qjcc.util.MD5;
import com.qjcc.util.NetWorkUtil;
import com.qjcc.util.PasswordUtil;
import com.qjcc.util.SessionUtil;
import com.qjcc.util.SharedPreferencesUtil;
import com.qjcc.util.StringUtils;
import com.qjcc.util.UIHelper;
import com.qjcc.util.UpdateManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.NetworkInterface;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by HAHAHA on 2016/7/14.
 */
public class LoginActivity extends Activity {

    //登陆是否成功
    private boolean isSucess = false;
    //返回信息
    private String msg = "";
    //延迟时间
    private static int delayTime = 3000;
    //登陆信息
    private Map loginMap = new HashMap();
    //没有网络异常信息
    private static String MSG_NO_NETWORK = "无网络连接，请确认联网后重试";
    // 是否退出
    private static boolean isExit = false;
    //progressDialog
    private ProgressCustomDialog progressCustomDialog;

    private boolean isClickHome = true;

    private Context myContext;

    //控件
    private Button loginButton;
    private EditText loginText;
    private EditText passwordText;

    //异步处理类
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    isExit = false;
                    break;

                case 1:
                    if (progressCustomDialog != null && progressCustomDialog.isShowing()) {
                        progressCustomDialog.dismiss();
                    }
                    UIHelper.ToastMessage(LoginActivity.this, LoginActivity.this.msg);
                    if (isSucess) {
                        directToMainActivity();
                    }
                    break;

                default:
                    super.handleMessage(msg);//这里最好对不需要或者不关心的消息抛给父类，避免丢失消息
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        myContext = this;

        // 解决华为选择照片、拍照闪退问题，动态增加权限
        List<String> pList = new ArrayList<>();
        int p1 = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int p2 = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        int p3 = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        if (p1 != PackageManager.PERMISSION_GRANTED) {
            pList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            pList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            pList.add(Manifest.permission.ACCESS_WIFI_STATE);
            pList.add(Manifest.permission.CHANGE_WIFI_STATE);
        }
        if (p2 != PackageManager.PERMISSION_GRANTED) {
            pList.add(Manifest.permission.CAMERA);
        }
        if (p3 != PackageManager.PERMISSION_GRANTED) {
            pList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            pList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        if (!pList.isEmpty()) {
            String[] ps = pList.toArray(new String[pList.size()]);
            ActivityCompat.requestPermissions(this, ps, 1);
        }

        //已经登陆过，直接进入主界面
        Map<String, String> users = SharedPreferencesUtil.getLoginUserMap(LoginActivity.this);
        if (!StringUtils.isEmpty(users.get("userId"))) {
            if ("0".equals(users.get("isReLogin"))) {
                directToMainActivity();
            } else {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, ReLoginActivity.class);
                startActivity(intent);
                LoginActivity.this.finish();
            }

        }else{
            //检查更新
            if(isClickHome){
                UpdateManager.getUpdateManager().checkAppUpdate(this, false, true);
                isClickHome = false;
            }else{
                UpdateManager.getUpdateManager().checkAppUpdate(this, false, false);
            }
        }

        loginText = (EditText) findViewById(R.id.loginName);
        passwordText = (EditText) findViewById(R.id.password);

        loginButton = (Button) findViewById(R.id.btn_login);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickLogin(v);
            }
        });
    }

    public void clickLogin(View view) {
        String name = loginText.getText().toString();
        String password = passwordText.getText().toString();
        // 判断用户名
        if (StringUtils.isEmpty(name)) {
            UIHelper.ToastMessage(view.getContext(), getString(R.string.msg_login_name_empty));
            return;
        }
        // 判断密码
        if (StringUtils.isEmpty(password)) {
            UIHelper.ToastMessage(view.getContext(), getString(R.string.msg_login_pwd_empty));
            return;
        }
        //生成密文密码
        String loginPwd = PasswordUtil.encrypt(name, password, PasswordUtil.getStaticSalt());
        //时间戳
        String time = String.valueOf(System.currentTimeMillis());
        //生成签名
        String signParam = "userName=" + name + "&password=" + loginPwd + "&time=" + time + "&key=" + AppUtil.KEY;
        String sign = MD5.MD5Encode(signParam);
        //mac
        String mac = getMacAddress();

        loginMap.put("mac", mac);
        loginMap.put("userName", name);
        loginMap.put("password", loginPwd);
        loginMap.put("sign", sign);
        loginMap.put("time", time);
        loginMap.put("tokenCode", null);
        loginMap.put("userId", null);

        // 开始登录
        if (NetWorkUtil.isConnect(LoginActivity.this)) {
            //打开progressDialog
            progressCustomDialog = ProgressCustomDialog.init(myContext, "登录中...", true, null);
            progressCustomDialog.setCanceledOnTouchOutside(false);
            progressCustomDialog.show();
            login(loginMap);
        } else {
            UIHelper.ToastMessage(LoginActivity.this, MSG_NO_NETWORK);
        }
    }

    /**
     * 登陆功能
     *
     * @param loginMap
     */
    private void login(final Map loginMap) {
        String url = this.getResources().getString(R.string.loginUrl);
//        HttpAccessUtilsVersion2.init(myContext);
        HttpAccessUtilsVersion2.callHttpAccess(this, url, loginMap, new HttpAccessUtilsVersion2.HttpAccessCallBack() {
            @Override
            public void callBack(Object result) {
                try {
                    Log.i("result", result.toString());
                    JSONObject resultJson = new JSONObject(result.toString());
                    String msg = resultJson.getString("msg");
                    boolean isSuccess = resultJson.getBoolean("success");
                    if (isSuccess) {
                        JSONObject jsonObject = resultJson.getJSONObject("obj");
                        Map userMap = new HashMap();
                        //用户ID
                        userMap.put("userId", jsonObject.optString("userId", null));
                        //登录名
                        userMap.put("userName", jsonObject.optString("userName", null));
                        //密码(涉及自动登陆使用)
                        userMap.put("password", loginMap.get("password"));
                        //token
                        userMap.put("tokenCode", jsonObject.optString("tokenCode", null));
                        //是否重新登陆
                        userMap.put("isReLogin", "0");

                        //保存sessionid 和 登录user信息到android xml中
                        SharedPreferencesUtil.saveSessionId(LoginActivity.this, "JSESSIONID=" + jsonObject.optString("jsessionid"));
                        SharedPreferencesUtil.saveUser(LoginActivity.this, userMap);

                        //同步session
                        SessionUtil.synSession(getApplicationContext());
                        if (loginMap.get("mac") != null) {
                            SharedPreferencesUtil.saveMac(myContext, loginMap.get("mac").toString());
                        }

                        isSucess = true;
                        delayTime = 3000;

                        Message mHandlermsg = new Message();
                        mHandlermsg.what = 1;
                        // 利用handler延迟发送更改状态信息
                        mHandler.sendMessageDelayed(mHandlermsg, delayTime);

                    } else {
                        if (progressCustomDialog != null && progressCustomDialog.isShowing()) {
                            progressCustomDialog.dismiss();
                        }
                        delayTime = 0;
                        UIHelper.ToastMessage(LoginActivity.this, msg);
                    }
                    LoginActivity.this.msg = msg;
                } catch (JSONException e) {
                    UIHelper.ToastMessage(LoginActivity.this, myContext.getResources().getString(R.string.login_failure));
                    delayTime = 0;
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 跳转主界面
     */
    private void directToMainActivity() {
        Intent intent = new Intent();
        intent.setClass(LoginActivity.this, IndexActivity.class);
        startActivity(intent);
        LoginActivity.this.finish();
    }

//    private String getMacAddress() {
//        try {
//            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
//            for (NetworkInterface nif : all) {
//                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
//
//                byte[] macBytes = nif.getHardwareAddress();
//                if (macBytes == null) {
//                    return "";
//                }
//
//                StringBuilder res1 = new StringBuilder();
//                for (byte b : macBytes) {
//                    res1.append(String.format("%02X:", b));
//                }
//
//                if (res1.length() > 0) {
//                    res1.deleteCharAt(res1.length() - 1);
//                }
//                return res1.toString();
//            }
//        } catch (Exception ex) {
//
//        }
//        return "02:00:00:00:00:00";
//    }

    private String getMacAddress(){
        String androidID = Settings.Secure.getString(myContext.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        if (!StringUtils.isEmpty(id)) {
            return id;
        }
        return "02:00:00:00:00:00";
    }

}
